package kr.co.cherryt.activity;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import kr.co.cherryt.cherryt.R;
import kr.co.cherryt.util.MemoryStatus;
import kr.co.cherryt.view.PlayerProgressBar;
import kr.co.cherryt.view.ResizableVideoView;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

//http://www.androidsnippets.com/memory-size-class-for-viewing-available-storage
public class AdPlayerActivity extends Activity implements View.OnClickListener
{
	Context context;
	
	RelativeLayout mInfoView;
	
	PlayerProgressBar mProgress;

	TextView mPlayedTime, mPlayTime;
	PlayPercentHandler mPercentHandler = null;
	Handler mTimerHandler = null;

	boolean bPause = false;
	int mCurrentPosition = -1;
	ProgressDialog mProgressDialog;
	
	Toast mToast = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ad_player_activity);

		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		
		context = this;

		mInfoView = (RelativeLayout)findViewById(R.id.infoview);
		((Button)findViewById(R.id.btnMovieClose)).setOnClickListener( this );

		mProgress = (PlayerProgressBar)findViewById(R.id.ad_playedbar);
		mPlayedTime = (TextView)findViewById(R.id.ad_playedtime);
		mPlayTime   = (TextView)findViewById(R.id.ad_playtime);

		Intent intent = getIntent();
		//String url = intent.getExtras().get("url").toString();
		//String control = intent.getExtras().get("control").toString();
		String strTitle = intent.getExtras().get("title").toString();
		
		((TextView)findViewById(R.id.ad_title)).setText(strTitle);
		
		//String strCompany = intent.getExtras().get("company").toString();
		//String strWriter = intent.getExtras().get("writer").toString();
		//((TextView)findViewById(R.id.ad_writer)).setText(strWriter);

		downloadContents();
	}        

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		final ResizableVideoView videoView = (ResizableVideoView) findViewById(R.id.videoview);
		mCurrentPosition = videoView.getCurrentPosition();
		findViewById(R.id.infoview).setVisibility(View.VISIBLE);
		
		if( bPause ) {
			//videoView.resume();
			//mTimerHandler.removeMessages(0);
			//mTimerHandler = null;

			if( mToast != null ) {
				mToast.cancel();
			}

			Intent intent = new Intent(context, DetailPopupActivity.class);
			setResult(1, intent);

			onDestroy();
			finish();
		}
		
		return super.onTouchEvent(event);
	}

	private void playVideoView(String path, String control) {
		final ResizableVideoView videoView = (ResizableVideoView) findViewById(R.id.videoview);

		//Log.d("cherryt", "playVideoView #1");
		
		DisplayMetrics displayMetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
		int pxWidth  = displayMetrics.widthPixels;
		int pxHeight = displayMetrics.heightPixels;
		videoView.initDisplayMeasureInfo(pxWidth, pxHeight);

		//Log.d("cherryt", "playVideoView #2");
		
		Uri uri = Uri.parse( path );
		videoView.setVideoURI(uri);

		//Log.d("cherryt", "playVideoView #3" + path);
		//Log.d("cherryt", "playVideoView #3" + uri);
		
		if( control.equals( new String("yes")))
		{
			MediaController mc = new MediaController(this);
			videoView.setMediaController(mc);
		}

		//Log.d("cherryt", "playVideoView #4");
		videoView.requestFocus();
		//Log.d("cherryt", "playVideoView #5");
		
		videoView.setOnPreparedListener( new OnPreparedListener() {           
			public void onPrepared(MediaPlayer mp) {
				//Log.d("cherryt", "onPrepared" + videoView.getCurrentPosition() );
				
				//hs-TODO// why? [BEGIN]
				try {
					Thread.sleep(500);
				} catch (final Throwable t) {}
				//hs-TODO// why? [END]
				
				mp.start();

				// 이전에 시청하던 곳으로 재 이동
				if( mCurrentPosition != -1 ) {
					mCurrentPosition -= 2000;		// 2초 뒤로 이동
					if( mCurrentPosition >= 0 )
					{
						videoView.seekTo( mCurrentPosition );
					}
				}
				else {
					mCurrentPosition = 0;
				}
				
				mPercentHandler = new PlayPercentHandler();
				mPercentHandler.sendEmptyMessageDelayed(0,  1000);

				int minutes, seconds;
				minutes = videoView.getDuration()/60000;
				seconds = (videoView.getDuration() - minutes * 60000)/1000;

				mPlayTime.setText( String.format("/%02d:%02d", minutes, seconds) );

				RelativeLayout preLoadingView = (RelativeLayout) findViewById(R.id.preloading_view);
				preLoadingView.setVisibility(View.INVISIBLE);
				
				//Log.d("cherryt", "onPrepared end" );
			}         
		});

		videoView.setOnCompletionListener( new OnCompletionListener() {
			public void onCompletion(MediaPlayer mp) {

				//Log.d("cherryt", "setOnCompletionListener 1" );
				
				mProgress.setProgress(100);

				if( mPercentHandler != null ) {
					Log.d("ad", "setOnCompletionListener 2" );
					mPercentHandler.removeMessages(0);
					mPercentHandler = null;
				}
				
				mToast = Toast.makeText(context, R.string.video_continue, Toast.LENGTH_LONG);
				mToast.show();
				
				mTimerHandler = new TimerHandler();
				mTimerHandler.sendEmptyMessageDelayed(0,  10000);
				
				bPause = true;
				
				//Log.d("cherryt", "setOnCompletionListener 3" );
				
//				Intent intent = new Intent(context, CherryTActivity.class);
//				setResult(1, intent);
//
//				onDestroy();
//				finish();
			}
		});
    }

	private void downloadContents() {
		Intent intent = getIntent();
		String url = intent.getExtras().get("url").toString();
		//String control = intent.getExtras().get("control").toString();
		String strTitle = intent.getExtras().get("title").toString();

		mProgressDialog = new ProgressDialog(context); 
		mProgressDialog.setMessage(strTitle + " 다운로드 중..."); 
		mProgressDialog.setIndeterminate(false); 
		mProgressDialog.setMax(100); 
		mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL); 
		mProgressDialog.show();
		
		myAsyncTask obj = new myAsyncTask (); 
		obj.execute(url);
    }
	
	private class myAsyncTask extends AsyncTask<String, Integer, String> {
		protected String doInBackground(String... urls) {
			int count;
			String strPath = null;
			try {
				
				URL url = new URL(urls[0]);
				//Log.d("cherryt", "down start URL0: " + url);
				
				String strTemp = url.toString();
				String strUrl[] = strTemp.split("title");
				
				URL realUrl = new URL( strUrl[0] );
				URLConnection connection = realUrl.openConnection();
				connection.connect();
				
				// 서버에 있는 파일의 길이를 구함
				int length = connection.getContentLength();
				
				//Log.d("cherryt", "down start [" + length + "] URL: " + realUrl);

				Uri uri = Uri.parse(strUrl[0]);
				
				List <String> uriList = uri.getPathSegments();
				int size = uriList.size();
				String strFileName = uriList.get(size-1);
				
				//http://cherryt.co.kr/ct/ad/movie/foblangshi.mp4

				// 저장공간이 충분하지 않은 경우, 스트리밍 방식으로 재생한다. 
				if( 102400000 < MemoryStatus.getAvailableExternalMemorySize() ) {
					
					// 체리티 폴더 생성
		    		strPath = Environment.getExternalStorageDirectory().getPath() + "/cherryt";
					
		    		File file = new File( strPath );
		    		if( !file.exists() )
		    		{
		    			file.mkdirs();		// 폴더 생성
		    		}

		    		// 파일명 생성
		    		strPath = Environment.getExternalStorageDirectory().getPath() + "/cherryt/" + strFileName;
					
		    		// 이미 다운로드 받은 파일이 존재하면, 그대로 재생한다.
		    		// 파일을 다운로드 받는 중에 정지한 경우 파일 크기가 달라진다. 
		    		// 이럴 경우는 처음부터 다시 받는다. 
		    		file = new File( strPath );
		    		if( !file.exists() || file.length() != length )
		    		{
						// 서버로부터 다운로드
						InputStream input = new BufferedInputStream(realUrl.openStream());
						OutputStream output = new FileOutputStream(strPath);
		
						byte data[] = new byte[4096];
						long total = 0;
						while(( count = input.read(data)) != -1 ) {
							total += count;
							// publishing the progress....
							publishProgress((int)(total*100/length));
							output.write(data, 0, count);
							//Log.d("cherryt", "down..." + total);
						}
		
						output.flush();
						output.close();
						input.close();
		    		}
		    		else
		    		{
		    			return strPath;
		    		}
				}
				else
				{
					return null;
				}
			} catch (Exception e) {
				//Log.d("cherryt", "down error: " + e.getMessage());
			}

			//path = Environment.getExternalStorageDirectory().getPath() + "/cherryt/1.mp4";
			//playVideoView(path, control);
			
			return strPath;
		}
		
		protected void onProgressUpdate(Integer... progress){                     
			mProgressDialog.setProgress(progress[0]);                 
		}
		
		protected void onPostExecute(String path) {
			//Log.d("cherryt", "onPostExecute #1");
			mProgressDialog.dismiss();
			if( path != null ) {
				playVideoView(path, "no");
				//Log.d("cherryt", "onPostExecute #2");
			}
			else {
				Toast.makeText(context, R.string.no_space, Toast.LENGTH_LONG).show();
				Intent intent = getIntent();
				String url = intent.getExtras().get("url").toString();
				String control = intent.getExtras().get("control").toString();
				playVideoView(url, control);
				//Log.d("cherryt", "onPostExecute #3");
			}
		}
		
		protected void onCancelled() {
			mProgressDialog.dismiss();
		}
	}
	
	@Override
	protected void onPause() {
		final ResizableVideoView videoView = (ResizableVideoView) findViewById(R.id.videoview);
		mCurrentPosition = videoView.getCurrentPosition();
		
		if( mPercentHandler != null ) 
		{
			mPercentHandler.removeMessages(0);
			mPercentHandler = null;
		}
		super.onPause();
	}

	public class PlayPercentHandler extends Handler {
		public void handleMessage(Message msg) 
		{
			if( msg.what == 0 ) {
				final ResizableVideoView videoView = (ResizableVideoView) findViewById(R.id.videoview);
				
				int minutes, seconds;
				minutes = videoView.getCurrentPosition()/60000;
				seconds = (videoView.getCurrentPosition() - minutes * 60000)/1000;

				mPlayedTime.setText( String.format("%02d:%02d", minutes, seconds) );
				mProgress.setProgress(videoView.getCurrentPosition()*100/videoView.getDuration());
				mPercentHandler.sendEmptyMessageDelayed(0,  1000);
				
				if (videoView.getCurrentPosition()*100/videoView.getDuration() >= 85 ) {
					mInfoView.setVisibility(View.VISIBLE);
				}
				else if( mCurrentPosition + 2000 < videoView.getCurrentPosition() ) {
					mInfoView.setVisibility(View.INVISIBLE);
				}
			}
		}
	}

	public class TimerHandler extends Handler {
		public void handleMessage(Message msg) 
		{
			mTimerHandler = null;
			
			Intent intent = new Intent(context, DetailPopupActivity.class);
			setResult(1, intent);

			onDestroy();
			finish();			
			return;
		}
	}
	
	public void onClick(View v) {
		if( v.getId() == R.id.btnMovieClose) {
			mProgress.setProgress(100);
			if( mPercentHandler!= null )
			{
				mPercentHandler.removeMessages(0);
				mPercentHandler = null;
			}

			Intent intent = new Intent(this, DetailPopupActivity.class);
			setResult(2, intent);

			onDestroy();
			finish();			
			return;
		}
	}

	@Override
	protected void onDestroy() {
		

		
		super.onDestroy();
	}	
}
